<template>
  <div class="grading-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-left">
        <h1>批改管理</h1>
        <p>批改学生考试，给出成绩和评语</p>
      </div>
      <div class="header-right">
        <el-button @click="batchGrading">
          <i class="fas fa-tasks"></i>
          批量批改
        </el-button>
        <el-button type="primary" @click="autoGrading">
          <i class="fas fa-magic"></i>
          智能批改
        </el-button>
      </div>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stats-grid">
      <div class="stat-card pending">
        <div class="stat-icon">
          <i class="fas fa-clock"></i>
        </div>
        <div class="stat-content">
          <h3>{{ stats.pending }}</h3>
          <p>待批改</p>
        </div>
      </div>
      
      <div class="stat-card graded">
        <div class="stat-icon">
          <i class="fas fa-check-circle"></i>
        </div>
        <div class="stat-content">
          <h3>{{ stats.graded }}</h3>
          <p>已批改</p>
        </div>
      </div>
      
      <div class="stat-card average">
        <div class="stat-icon">
          <i class="fas fa-chart-line"></i>
        </div>
        <div class="stat-content">
          <h3>{{ stats.averageScore }}</h3>
          <p>平均分</p>
        </div>
      </div>
      
      <div class="stat-card total">
        <div class="stat-icon">
          <i class="fas fa-users"></i>
        </div>
        <div class="stat-content">
          <h3>{{ stats.total }}</h3>
          <p>总提交数</p>
        </div>
      </div>
    </div>
    
    <!-- 搜索和筛选 -->
    <div class="search-section">
      <div class="search-left">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索考试名称..."
          :prefix-icon="Search"
          clearable
          @input="handleSearch"
        />
        <el-select v-model="statusFilter" placeholder="考试状态" clearable>
          <el-option label="全部状态" value="" />
          <el-option label="进行中" value="ongoing" />
          <el-option label="已结束" value="finished" />
          <el-option label="未开始" value="pending" />
        </el-select>
        <el-select v-model="sortBy" placeholder="排序方式">
          <el-option label="考试时间" value="examTime" />
          <el-option label="考试名称" value="examName" />
          <el-option label="创建时间" value="createTime" />
        </el-select>
      </div>
      <div class="search-right">
        <el-button :icon="Refresh" @click="loadExamAssignments">刷新</el-button>
      </div>
    </div>
    
    <!-- 考试安排列表 -->
    <div class="exam-assignments-list">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <el-skeleton :rows="3" animated />
        <el-skeleton :rows="3" animated />
        <el-skeleton :rows="3" animated />
      </div>
      
      <!-- 考试列表 -->
      <div 
        v-else 
        v-for="assignment in filteredAssignments" 
        :key="assignment.id" 
        class="assignment-card"
        :class="assignment.status"
      >
        <div class="assignment-header">
          <div class="exam-info">
            <div class="exam-icon">
              <i class="fas fa-file-alt"></i>
            </div>
            <div class="exam-details">
              <h4>{{ assignment.examName }}</h4>
              <p>{{ assignment.courseName }} | {{ assignment.className }}</p>
            </div>
          </div>
          
          <div class="assignment-meta">
            <el-tag 
              :type="getStatusTagType(assignment.status)"
              size="small"
            >
              {{ getStatusLabel(assignment.status) }}
            </el-tag>
            <span class="exam-time">{{ formatDateTime(assignment.examTime) }}</span>
          </div>
        </div>
        
        <div class="assignment-content">
          <div class="assignment-stats">
            <div class="stat-item">
              <span class="label">考试时长：</span>
              <span class="value">{{ assignment.duration }} 分钟</span>
            </div>
            <div class="stat-item">
              <span class="label">参考学生：</span>
              <span class="value">{{ assignment.totalStudents }} 人</span>
            </div>
            <div class="stat-item">
              <span class="label">已提交：</span>
              <span class="value">{{ assignment.submittedStudents }} 人</span>
            </div>
            <div class="stat-item">
              <span class="label">待批改：</span>
              <span class="value pending-count">{{ assignment.pendingGrading }} 人</span>
            </div>
            <div class="stat-item">
              <span class="label">已批改：</span>
              <span class="value graded-count">{{ assignment.gradedStudents }} 人</span>
            </div>
          </div>
          
          <div v-if="assignment.description" class="assignment-description">
            <h5>考试说明：</h5>
            <p>{{ assignment.description }}</p>
          </div>
        </div>
        
        <div class="assignment-actions">
          <el-button 
            v-if="assignment.submittedStudents > 0"
            size="small" 
            type="primary" 
            @click="startGradingExam(assignment)"
          >
            开始批改
          </el-button>

          <el-button 
            v-if="assignment.status === 'finished'"
            size="small" 
            @click="exportResults(assignment)"
          >
            导出成绩
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="totalAssignments"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 空状态 -->
    <div v-if="!loading && filteredAssignments.length === 0" class="empty-state">
      <i class="fas fa-calendar-alt"></i>
      <h3>暂无考试安排</h3>
      <p>当前筛选条件下没有找到考试安排</p>
    </div>
    
    <!-- 批改对话框 -->
    <el-dialog
      v-model="showGradingDialog"
      :title="`批改 - ${currentSubmission?.student?.name}`"
      width="1000px"
      :close-on-click-modal="false"
    >
      <div v-if="currentSubmission" class="grading-content">
        <!-- 考试信息 -->
        <div class="exam-info">
          <h3>{{ currentSubmission.exam.name }}</h3>
          <div class="exam-meta">
            <span>提交时间：{{ formatDateTime(currentSubmission.submitTime) }}</span>
            <span>答题时长：{{ formatDuration(currentSubmission.duration) }}</span>
          </div>
        </div>
        
        <!-- 题目列表 -->
        <div class="questions-grading">
          <div 
            v-for="(answer, index) in currentSubmission.answers" 
            :key="index" 
            class="question-grading"
          >
            <div class="question-header">
              <h4>第 {{ index + 1 }} 题 ({{ answer.question.score }} 分)</h4>
              <el-tag :type="getQuestionTypeTag(answer.question.type)">
                {{ getQuestionTypeLabel(answer.question.type) }}
              </el-tag>
            </div>
            
            <div class="question-content">
              <div class="question-text" v-html="answer.question.content"></div>
              
              <!-- 选择题 -->
              <div v-if="['single', 'multiple'].includes(answer.question.type)" class="choice-question">
                <div class="options">
                  <div 
                    v-for="(option, optIndex) in answer.question.options" 
                    :key="optIndex" 
                    class="option"
                    :class="{
                      correct: answer.question.correctAnswers.includes(optIndex),
                      selected: answer.selectedOptions?.includes(optIndex),
                      wrong: answer.selectedOptions?.includes(optIndex) && !answer.question.correctAnswers.includes(optIndex)
                    }"
                  >
                    <span class="option-label">{{ String.fromCharCode(65 + optIndex) }}.</span>
                    <span class="option-text">{{ option }}</span>
                    <i v-if="answer.question.correctAnswers.includes(optIndex)" class="fas fa-check correct-icon"></i>
                    <i v-if="answer.selectedOptions?.includes(optIndex) && !answer.question.correctAnswers.includes(optIndex)" class="fas fa-times wrong-icon"></i>
                  </div>
                </div>
              </div>
              
              <!-- 判断题 -->
              <div v-else-if="answer.question.type === 'boolean'" class="boolean-question">
                <div class="answer-comparison">
                  <div class="student-answer">
                    <span class="label">学生答案：</span>
                    <el-tag :type="answer.booleanAnswer ? 'success' : 'danger'">
                      {{ answer.booleanAnswer ? '正确' : '错误' }}
                    </el-tag>
                  </div>
                  <div class="correct-answer">
                    <span class="label">正确答案：</span>
                    <el-tag :type="answer.question.correctAnswer ? 'success' : 'danger'">
                      {{ answer.question.correctAnswer ? '正确' : '错误' }}
                    </el-tag>
                  </div>
                </div>
              </div>
              
              <!-- 填空题 -->
              <div v-else-if="answer.question.type === 'fill'" class="fill-question">
                <div class="answer-comparison">
                  <div class="student-answer">
                    <span class="label">学生答案：</span>
                    <div class="fill-answers">
                      <el-tag 
                        v-for="(ans, ansIndex) in answer.fillAnswers" 
                        :key="ansIndex"
                        class="answer-tag"
                      >
                        {{ ans }}
                      </el-tag>
                    </div>
                  </div>
                  <div class="correct-answer">
                    <span class="label">参考答案：</span>
                    <div class="fill-answers">
                      <el-tag 
                        v-for="(ans, ansIndex) in answer.question.correctAnswers" 
                        :key="ansIndex"
                        type="success"
                        class="answer-tag"
                      >
                        {{ ans }}
                      </el-tag>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 简答题 -->
              <div v-else-if="answer.question.type === 'essay'" class="essay-question">
                <div class="student-answer">
                  <h5>学生答案：</h5>
                  <div class="essay-content">{{ answer.essayAnswer || '未作答' }}</div>
                </div>
                <div class="reference-answer">
                  <h5>参考答案：</h5>
                  <div class="essay-content">{{ answer.question.referenceAnswer }}</div>
                </div>
              </div>
            </div>
            
            <!-- 评分区域 -->
            <div class="scoring-section">
              <div class="score-input">
                <span class="label">得分：</span>
                <el-input-number
                  v-model="answer.score"
                  :min="0"
                  :max="answer.question.score"
                  :precision="1"
                  size="small"
                />
                <span class="max-score">/ {{ answer.question.score }} 分</span>
              </div>
              <div class="comment-input">
                <span class="label">评语：</span>
                <el-input
                  v-model="answer.comment"
                  placeholder="请输入评语（可选）"
                  size="small"
                />
              </div>
            </div>
          </div>
        </div>
        
        <!-- 总评 -->
        <div class="overall-grading">
          <div class="total-score">
            <span class="label">总分：</span>
            <span class="score">{{ calculateTotalScore() }}</span>
            <span class="max-score">/ {{ calculateMaxScore() }} 分</span>
          </div>
          <div class="overall-comment">
            <span class="label">总评：</span>
            <el-input
              v-model="overallComment"
              type="textarea"
              :rows="3"
              placeholder="请输入总体评语"
            />
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="showGradingDialog = false">取消</el-button>
        <el-button @click="saveAsDraft">保存草稿</el-button>
        <el-button type="primary" @click="submitGrading" :loading="submitting">
          提交批改
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 批量批改对话框 -->
    <el-dialog
      v-model="showBatchDialog"
      title="批量批改"
      width="600px"
    >
      <div class="batch-grading">
        <el-alert
          title="批量批改说明"
          type="info"
          :closable="false"
          show-icon
        >
          <p>批量批改将自动批改所有客观题（单选、多选、判断、填空），主观题仍需手动批改。</p>
        </el-alert>
        
        <div class="batch-options">
          <el-form label-width="120px">
            <el-form-item label="批改范围">
              <el-radio-group v-model="batchScope">
                <el-radio label="all">全部待批改</el-radio>
                <el-radio label="exam">指定考试</el-radio>
                <el-radio label="selected">已选择的</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item v-if="batchScope === 'exam'" label="选择考试">
              <el-select v-model="batchExamId" placeholder="请选择考试">
                <el-option 
                  v-for="exam in exams" 
                  :key="exam.id" 
                  :label="exam.name" 
                  :value="exam.id" 
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="批改选项">
              <el-checkbox-group v-model="batchOptions">
                <el-checkbox label="autoScore">自动评分客观题</el-checkbox>
                <el-checkbox label="addComment">添加默认评语</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-form>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="showBatchDialog = false">取消</el-button>
        <el-button type="primary" @click="executeBatchGrading" :loading="batchProcessing">
          开始批量批改
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getToken } from '@/utils/auth'
import { getExamsNeedingGrading } from '@/api/grading/gradingUI'
// import { 
//   getSubmissions, 
//   gradeSubmission, 
//   batchGradeSubmissions,
//   getExams
// } from '@/api/rbac/admin'

const router = useRouter()

const searchKeyword = ref('')
const statusFilter = ref('')
const sortBy = ref('examTime')
const currentPage = ref(1)
const pageSize = ref(20)
const totalAssignments = ref(0)
const showGradingDialog = ref(false)
const showBatchDialog = ref(false)
const submitting = ref(false)
const batchProcessing = ref(false)
const currentAssignment = ref(null)
const overallComment = ref('')
const batchScope = ref('all')
const batchExamId = ref('')
const batchOptions = ref(['autoScore'])

const stats = ref({
  pending: 5,
  graded: 12,
  averageScore: 78.5,
  total: 17
})

const examAssignments = ref([])
const loading = ref(false)

const filteredAssignments = computed(() => {
  let result = examAssignments.value
  
  if (searchKeyword.value) {
    result = result.filter(a => 
      a.examName.includes(searchKeyword.value) ||
      a.courseName.includes(searchKeyword.value)
    )
  }
  
  if (statusFilter.value) {
    result = result.filter(a => a.status === statusFilter.value)
  }
  
  // 排序
  result.sort((a, b) => {
    switch (sortBy.value) {
      case 'examTime':
        return new Date(b.examTime) - new Date(a.examTime)
      case 'examName':
        return a.examName.localeCompare(b.examName)
      case 'createTime':
        return new Date(b.examTime) - new Date(a.examTime) // 暂时使用examTime
      default:
        return 0
    }
  })
  
  return result
})

const getStatusLabel = (status) => {
  const labels = {
    pending: '未开始',
    ongoing: '进行中',
    finished: '已结束'
  }
  return labels[status] || status
}

const getStatusTagType = (status) => {
  const types = {
    pending: 'info',
    ongoing: 'warning',
    finished: 'success'
  }
  return types[status] || 'info'
}

const getQuestionTypeLabel = (type) => {
  const labels = {
    single: '单选题',
    multiple: '多选题',
    boolean: '判断题',
    fill: '填空题',
    essay: '简答题'
  }
  return labels[type] || type
}

const getQuestionTypeTag = (type) => {
  const types = {
    single: 'primary',
    multiple: 'success',
    boolean: 'warning',
    fill: 'info',
    essay: 'danger'
  }
  return types[type] || 'primary'
}


const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const handleSizeChange = (size) => {
  pageSize.value = size
  loadExamAssignments()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadExamAssignments()
}

const viewExamDetails = (assignment) => {
  // 查看考试详情
  ElMessage.info('查看考试详情功能开发中...')
}

const startGradingExam = (assignment) => {
  // 跳转到批改详情页面开始批改
  router.push({
    name: 'TeacherGradingDetail',
    query: { examId: assignment.examId }
  })
}

const viewGradingProgress = (assignment) => {
  // 查看批改进度
  router.push({
    name: 'TeacherGradingDetail',
    query: { examId: assignment.examId }
  })
}

const exportResults = async (assignment) => {
  try {
    // 检查考试状态
    if (assignment.status !== 'finished') {
      ElMessage.warning('只能导出已结束的考试成绩')
      return
    }
    
    // 检查是否有已批改的学生
    if (assignment.gradedStudents === 0) {
      ElMessage.warning('暂无已批改的学生，无法导出成绩')
      return
    }
    
    // 检查是否所有学生都已批改完成
    if (assignment.gradedStudents < assignment.submittedStudents) {
      const result = await ElMessageBox.confirm(
        `当前批改进度：${assignment.gradedStudents}/${assignment.submittedStudents}，还有 ${assignment.submittedStudents - assignment.gradedStudents} 名学生未完成批改。\n\n确定要导出当前成绩吗？未批改的学生成绩将显示为空。`,
        '批改未完成提醒',
        {
          confirmButtonText: '确定导出',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: false
        }
      )
      
      if (!result) {
        return
      }
    }
    
    const response = await fetch(`/api/grade-export/excel/${assignment.examId}`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${getToken()}`
      }
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `考试成绩_${assignment.examName}.xlsx`
    document.body.appendChild(a)
    a.click()
    window.URL.revokeObjectURL(url)
    document.body.removeChild(a)
    
    ElMessage.success('导出成功')
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消导出
      return
    }
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  }
}

const markForReview = async (submission) => {
  try {
    await ElMessageBox.confirm(
      '确定要标记此提交为需要复查吗？',
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    submission.status = 'review'
    ElMessage.success('已标记为需要复查')
  } catch (error) {
    // 用户取消
  }
}

const calculateTotalScore = () => {
  if (!currentSubmission.value?.answers) return 0
  return currentSubmission.value.answers.reduce((total, answer) => {
    return total + (answer.score || 0)
  }, 0)
}

const calculateMaxScore = () => {
  if (!currentSubmission.value?.answers) return 0
  return currentSubmission.value.answers.reduce((total, answer) => {
    return total + answer.question.score
  }, 0)
}

const saveAsDraft = async () => {
  try {
    // 保存草稿逻辑
    ElMessage.success('草稿保存成功')
  } catch (error) {
    ElMessage.error('保存草稿失败')
  }
}

const submitGrading = async () => {
  try {
    submitting.value = true
    
    const gradingData = {
      submissionId: currentSubmission.value.id,
      answers: currentSubmission.value.answers.map(answer => ({
        questionId: answer.question.id,
        score: answer.score,
        comment: answer.comment
      })),
      totalScore: calculateTotalScore(),
      comment: overallComment.value
    }
    
    await gradeSubmission(gradingData)
    
    // 更新本地数据
    currentSubmission.value.status = 'graded'
    currentSubmission.value.score = calculateTotalScore()
    currentSubmission.value.comment = overallComment.value
    
    showGradingDialog.value = false
    ElMessage.success('批改提交成功')
  } catch (error) {
    ElMessage.error('提交批改失败')
  } finally {
    submitting.value = false
  }
}

const batchGrading = () => {
  showBatchDialog.value = true
}

const autoGrading = async () => {
  try {
    await ElMessageBox.confirm(
      '智能批改将自动批改所有客观题，是否继续？',
      '确认智能批改',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    // 执行智能批改
    ElMessage.success('智能批改已完成')
  } catch (error) {
    // 用户取消
  }
}

const executeBatchGrading = async () => {
  try {
    batchProcessing.value = true
    
    const batchData = {
      scope: batchScope.value,
      examId: batchExamId.value,
      options: batchOptions.value
    }
    
    await batchGradeSubmissions(batchData)
    
    showBatchDialog.value = false
    loadSubmissions()
    ElMessage.success('批量批改完成')
  } catch (error) {
    ElMessage.error('批量批改失败')
  } finally {
    batchProcessing.value = false
  }
}

const formatDateTime = (dateTime) => {
  return new Date(dateTime).toLocaleString('zh-CN')
}

const formatDuration = (seconds) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  return `${hours}小时${minutes}分钟`
}

// 加载考试列表
const loadExamAssignments = async () => {
  try {
    loading.value = true
    const response = await getExamsNeedingGrading()
    
    if (response.code === 200) {
      // 将后端返回的数据转换为前端需要的格式
      examAssignments.value = response.data.map(exam => ({
        id: exam.examId,
        examId: exam.examId,
        examName: exam.examTitle,
        courseName: '', // 后端暂未返回课程名称
        className: '', // 后端暂未返回班级名称
        status: exam.pendingStudents > 0 ? 'ongoing' : 'finished',
        examTime: '', // 后端暂未返回考试时间
        duration: 0, // 后端暂未返回考试时长
        totalStudents: exam.totalStudents,
        submittedStudents: exam.totalStudents, // 假设所有学生都已提交
        pendingGrading: exam.pendingStudents,
        gradedStudents: exam.completedStudents,
        description: '' // 后端暂未返回考试描述
      }))
      
      // 更新统计数据
      updateStats()
    } else {
      ElMessage.error(response.message || '获取考试列表失败')
    }
  } catch (error) {
    console.error('获取考试列表失败:', error)
    ElMessage.error('获取考试列表失败')
  } finally {
    loading.value = false
  }
}

// 更新统计数据
const updateStats = () => {
  const totalPending = examAssignments.value.reduce((sum, exam) => sum + exam.pendingGrading, 0)
  const totalGraded = examAssignments.value.reduce((sum, exam) => sum + exam.gradedStudents, 0)
  const totalStudents = examAssignments.value.reduce((sum, exam) => sum + exam.totalStudents, 0)
  
  stats.value = {
    pending: totalPending,
    graded: totalGraded,
    averageScore: 0, // 暂时设为0，需要额外接口获取
    total: totalStudents
  }
}

onMounted(() => {
  loadExamAssignments()
})
</script>

<style lang="scss" scoped>
.grading-page {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 32px;
  
  .header-left {
    h1 {
      font-size: 28px;
      font-weight: 700;
      color: var(--neutral-700);
      margin-bottom: 8px;
    }
    
    p {
      color: var(--neutral-500);
      font-size: 16px;
    }
  }
  
  .header-right {
    display: flex;
    gap: 12px;
  }
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 32px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  gap: 16px;
  
  .stat-icon {
    width: 50px;
    height: 50px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    
    i {
      font-size: 20px;
      color: white;
    }
  }
  
  &.pending .stat-icon {
    background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
  }
  
  &.graded .stat-icon {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  }
  
  &.average .stat-icon {
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  }
  
  &.total .stat-icon {
    background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%);
  }
  
  .stat-content {
    h3 {
      font-size: 24px;
      font-weight: 700;
      color: var(--neutral-700);
      margin-bottom: 4px;
    }
    
    p {
      color: var(--neutral-500);
      font-size: 14px;
    }
  }
}

.search-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .search-left {
    display: flex;
    gap: 16px;
    flex-wrap: wrap;
    
    .el-input {
      width: 250px;
    }
    
    .el-select {
      width: 150px;
    }
  }
}

.exam-assignments-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 32px;
}

.loading-state {
  display: flex;
  flex-direction: column;
  gap: 16px;
  
  .el-skeleton {
    background: white;
    border-radius: 12px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  }
}

.assignment-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  
  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  }
  
  &.pending {
    border-left: 4px solid #6b7280;
  }
  
  &.ongoing {
    border-left: 4px solid #f59e0b;
  }
  
  &.finished {
    border-left: 4px solid #10b981;
  }
}

.assignment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  
  .exam-info {
    display: flex;
    align-items: center;
    gap: 12px;
    
    .exam-icon {
      width: 40px;
      height: 40px;
      background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      
      i {
        color: white;
        font-size: 16px;
      }
    }
    
    .exam-details {
      h4 {
        font-size: 16px;
        font-weight: 600;
        color: var(--neutral-700);
        margin-bottom: 4px;
      }
      
      p {
        font-size: 13px;
        color: var(--neutral-500);
      }
    }
  }
  
  .assignment-meta {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 8px;
    
    .exam-time {
      font-size: 12px;
      color: var(--neutral-400);
    }
  }
}

.assignment-content {
  margin-bottom: 20px;
  
  .assignment-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
    gap: 16px;
    margin-bottom: 16px;
    
    .stat-item {
      display: flex;
      justify-content: space-between;
      
      .label {
        color: var(--neutral-500);
        font-size: 13px;
      }
      
      .value {
        color: var(--neutral-700);
        font-weight: 500;
        font-size: 13px;
        
        &.pending-count {
          color: #f59e0b;
          font-weight: 600;
        }
        
        &.graded-count {
          color: #10b981;
          font-weight: 600;
        }
      }
    }
  }
  
  .assignment-description {
    background: var(--neutral-50);
    border-radius: 8px;
    padding: 12px;
    
    h5 {
      font-size: 13px;
      color: var(--neutral-600);
      margin-bottom: 8px;
    }
    
    p {
      font-size: 14px;
      color: var(--neutral-700);
      line-height: 1.5;
    }
  }
}

.assignment-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 32px;
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  
  i {
    font-size: 64px;
    color: var(--neutral-300);
    margin-bottom: 24px;
  }
  
  h3 {
    font-size: 20px;
    color: var(--neutral-500);
    margin-bottom: 12px;
  }
  
  p {
    color: var(--neutral-400);
    margin-bottom: 24px;
  }
}

.grading-content {
  max-height: 70vh;
  overflow-y: auto;
  
  .exam-info {
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid var(--neutral-200);
    
    h3 {
      font-size: 18px;
      font-weight: 600;
      color: var(--neutral-700);
      margin-bottom: 8px;
    }
    
    .exam-meta {
      display: flex;
      gap: 24px;
      font-size: 13px;
      color: var(--neutral-500);
    }
  }
}

.questions-grading {
  .question-grading {
    margin-bottom: 32px;
    padding: 20px;
    border: 1px solid var(--neutral-200);
    border-radius: 8px;
    
    .question-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      
      h4 {
        font-size: 16px;
        font-weight: 600;
        color: var(--neutral-700);
      }
    }
    
    .question-content {
      margin-bottom: 20px;
      
      .question-text {
        font-size: 15px;
        line-height: 1.6;
        color: var(--neutral-700);
        margin-bottom: 16px;
      }
    }
    
    .choice-question {
      .options {
        .option {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 8px 12px;
          margin-bottom: 8px;
          border-radius: 6px;
          background: var(--neutral-50);
          position: relative;
          
          &.correct {
            background: rgba(22, 163, 74, 0.1);
            border: 1px solid rgba(22, 163, 74, 0.2);
          }
          
          &.selected {
            background: rgba(59, 130, 246, 0.1);
            border: 1px solid rgba(59, 130, 246, 0.2);
          }
          
          &.wrong {
            background: rgba(239, 68, 68, 0.1);
            border: 1px solid rgba(239, 68, 68, 0.2);
          }
          
          .option-label {
            font-weight: 600;
            color: var(--neutral-600);
            min-width: 20px;
          }
          
          .option-text {
            flex: 1;
            color: var(--neutral-700);
          }
          
          .correct-icon {
            color: var(--success-color);
          }
          
          .wrong-icon {
            color: var(--error-color);
          }
        }
      }
    }
    
    .boolean-question,
    .fill-question {
      .answer-comparison {
        display: flex;
        flex-direction: column;
        gap: 12px;
        
        .student-answer,
        .correct-answer {
          display: flex;
          align-items: center;
          gap: 8px;
          
          .label {
            font-weight: 600;
            color: var(--neutral-600);
            min-width: 80px;
          }
          
          .fill-answers {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
          }
        }
      }
    }
    
    .essay-question {
      .student-answer,
      .reference-answer {
        margin-bottom: 16px;
        
        h5 {
          font-size: 14px;
          font-weight: 600;
          color: var(--neutral-600);
          margin-bottom: 8px;
        }
        
        .essay-content {
          padding: 12px;
          background: var(--neutral-50);
          border-radius: 6px;
          color: var(--neutral-700);
          line-height: 1.6;
          min-height: 60px;
        }
      }
    }
    
    .scoring-section {
      display: flex;
      gap: 24px;
      align-items: center;
      padding-top: 16px;
      border-top: 1px solid var(--neutral-200);
      
      .score-input {
        display: flex;
        align-items: center;
        gap: 8px;
        
        .label {
          font-weight: 600;
          color: var(--neutral-600);
        }
        
        .max-score {
          color: var(--neutral-500);
          font-size: 13px;
        }
      }
      
      .comment-input {
        flex: 1;
        display: flex;
        align-items: center;
        gap: 8px;
        
        .label {
          font-weight: 600;
          color: var(--neutral-600);
          white-space: nowrap;
        }
      }
    }
  }
}

.overall-grading {
  padding: 20px;
  background: var(--neutral-50);
  border-radius: 8px;
  margin-top: 24px;
  
  .total-score {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 16px;
    
    .label {
      font-weight: 600;
      color: var(--neutral-600);
    }
    
    .score {
      font-size: 20px;
      font-weight: 700;
      color: var(--primary-color);
    }
    
    .max-score {
      color: var(--neutral-500);
    }
  }
  
  .overall-comment {
    display: flex;
    flex-direction: column;
    gap: 8px;
    
    .label {
      font-weight: 600;
      color: var(--neutral-600);
    }
  }
}

.batch-grading {
  .batch-options {
    margin-top: 20px;
  }
}

@media (max-width: 768px) {
  .search-section {
    .search-left {
      flex-direction: column;
      width: 100%;
      
      .el-input,
      .el-select {
        width: 100%;
      }
    }
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
    
    .header-right {
      justify-content: flex-start;
    }
  }
  
  .assignment-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
    
    .assignment-meta {
      align-items: flex-start;
    }
  }
  
  .assignment-stats {
    grid-template-columns: 1fr;
  }
  
  .scoring-section {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
}
</style>